/**
 * jQuery json-viewer
 * @author: Alexandre Bodelot <alexandre.bodelot@gmail.com>
 */
;(function ($) {
  function Table() {
    console.log("inininininininini")
    var TClass = {}
    var Tool = {}
    var DataStore = {}
    var Option = {}
    Tool.createHeader = function (htmls, data) {
      htmls.push("<tr>")
      for (var i in data) {
        htmls.push("<th>" + data[i] + "</th>")
      }
      htmls.push("</tr>")
    }
    Tool.createRow = function (htmls, data) {
      htmls.push("<tr>")
      for (var i in data) {
        htmls.push("<td>" + data[i] + "</td>")
      }
      htmls.push("</tr>")
    }
    Tool.render = function (id, tag) {
      var htmls = []
      var option = Option[id]
      if (option["title"] != null) {
        htmls.push('<div class="title">' + option["title"] + "</div>")
      }
      htmls.push("<table>")
      Tool.createHeader(htmls, DataStore[id]["header"])
      for (var i in DataStore[id]["data"]) {
        Tool.createRow(htmls, DataStore[id]["data"][i])
      }
      htmls.push("</table>")
      tag.empty().append(htmls.join(""))
      Tool.setStyle(id, tag)
    }
    Tool.setStyle = function (id, tag) {
      var option = Option[id]
      tag.find(".title").css({
        "font-weight": "bold",
        "text-align": "center",
        color: option["titleColor"],
        "font-size": option["titleSize"],
      })
      tag.find("table").css({
        width: "100%",
      })
      tag.find("th").css({
        color: option["headerColor"],
        "background-color": option["headerBgColor"],
        "font-size": option["headerSize"],
      })
      tag.find("tr td").css({
        color: option["color"],
        "font-size": option["size"],
        "text-align": option["align"],
      })
      tag.find("tr:even td").css({
        "background-color": option["evenBgColor"],
      })
      tag.find("tr:odd td").css({
        "background-color": option["oddBgColor"],
      })
      if (option["rowHeight"] != null) {
        tag.find("tr").find("th:eq(0)").css("height", option["rowHeight"])
        tag.find("tr").find("td:eq(0)").css("height", option["rowHeight"])
      }
      if (option["columnWidth"] != null) {
        var td = tag.find("tr").find("th")
        $.each(td, function (i) {
          $(this).css("width", option["columnWidth"][i] + "%")
        })
      }
    }
    Tool.getValue = function (value, defalutValue) {
      if (typeof value == "undefined") {
        return defalutValue
      } else {
        return value
      }
    }
    TClass.init = function (option) {
      var id = option["id"]
      var tag = $("#" + id)
      var header = option["header"]
      var data = option["data"]
      DataStore[id] = {
        header: header,
        data: data,
      }
      Option[id] = {
        title: Tool.getValue(option["title"], null),
        titleColor: Tool.getValue(option["titleColor"], "black"),
        titleSize: Tool.getValue(option["titleSize"], 16),
        headerColor: Tool.getValue(option["headerColor"], "black"),
        headerBgColor: Tool.getValue(option["headerBgColor"], "#A2FD9A"),
        headerSize: Tool.getValue(option["headerSize"], 16),
        color: Tool.getValue(option["color"], "black"),
        size: Tool.getValue(option["size"], 16),
        align: Tool.getValue(option["align"], "center"),
        evenBgColor: Tool.getValue(option["evenBgColor"], "#E3F4FD"),
        oddBgColor: Tool.getValue(option["oddBgColor"], "#FDF0E6"),
        rowHeight: Tool.getValue(option["rowHeight"], 34),
        columnWidth: Tool.getValue(option["columnWidth"], null),
      }
      Tool.render(id, tag)
    }
    TClass.getValue = function (id, row, column) {
      return DataStore[id]["data"][row - 1][column - 1]
    }
    TClass.setValue = function (id, row, column, value) {
      DataStore[id]["data"][row - 1][column - 1] = value
    }
    TClass.getValues = function (id) {
      return DataStore[id]["data"]
    }
    TClass.addRow = function (id, data) {
      DataStore[id]["data"].push(data)
    }
    TClass.deleteRow = function (id, row) {
      DataStore[id]["data"].splice(row - 1, 1)
    }
    TClass.getRowCount = function (id) {
      return DataStore[id]["data"].length
    }
    TClass.render = function (id) {
      Tool.render(id, $("#" + id))
    }
    return TClass
  }
  /**
   * Check if arg is either an array with at least 1 element, or a dict with at least 1 key
   * @return boolean
   */
  function isCollapsable(arg) {
    return arg instanceof Object && Object.keys(arg).length > 0
  }

  /**
   * Check if a string represents a valid url
   * @return boolean
   */
  function isUrl(string) {
    var regexp = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
    return regexp.test(string)
  }
  function uuid() {
    var s = []
    var hexDigits = "0123456789abcdef"
    for (var i = 0; i < 36; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
    }
    s[14] = "4" // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-"

    var uuid = s.join("")
    return uuid
  }
  /**
   * Transform a json object into html representation
   * @return string
   */

  function json2html(json, options) {
    var html = ""
    if (typeof json === "string") {
      /* Escape tags */
      json = json.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
      if (isUrl(json)) {
        html += '<a href="' + json + '" class="json-string">' + json + "</a>"
      } else {
        //////////console.log("字符串 的 value", json)
        html += '<span class="json-string">"' + json + '"</span>'
      }
    } else if (typeof json === "number") {
      /////////console.log("number 的 value", json)
      html += '<span class="json-literal">' + json + "</span>"
    } else if (typeof json === "boolean") {
      /////////console.log("boolean 的 value", json)
      html += '<span class="json-literal">' + json + "</span>"
    } else if (json === null) {
      /////////console.log("null 的 value", json)
      html += '<span class="json-literal">null</span>'
    } else if (json instanceof Array) {
      console.log("json", json)
      // let tId = uuid()
      // html += "<div id=" + tId + "></div>"
      // tableIdArray.push({ id: tId, data: json })

      if (json.length > 0) {
        html += '[<ol class="json-array">'
        for (var i = 0; i < json.length; ++i) {
          html += "<li>"
          /* Add toggle button if item is collapsable */
          if (isCollapsable(json[i])) {
            html += '<a href class="json-toggle"></a>'
          }
          html += json2html(json[i], options)
          /* Add comma if item is not last */
          if (i < json.length - 1) {
            html += ","
          }
          html += "</li>"
        }
        html += "</ol>]"
      } else {
        html += "[]"
      }
    } else if (typeof json === "object") {
      var key_count = Object.keys(json).length
      if (key_count > 0) {
        html += '{<ul class="json-dict">'
        for (var key in json) {
          if (json.hasOwnProperty(key)) {
            html += "<li>"
            var keyRepr = options.withQuotes ? '<span class="json-string">"' + key + '"</span>' : key
            /* Add toggle button if item is collapsable */
            let strArray = null
            strArray = keyRepr.split("?$") //拆分注释
            if (isCollapsable(json[key])) {
              html += '<a href class="json-toggle">' + strArray[0] + "</a>"
            } else {
              html += strArray[0]
            }
            if (strArray && strArray[1] && options.showType) {
              //如果key种有注释--则拼接注释
              html +=
                ": " +
                json2html(json[key], options) +
                '<span class="jsontip"><span>\\\\</span>' +
                strArray[1] +
                "</span>"
            } else {
              html += ": " + json2html(json[key], options)
            }
            /* Add comma if item is not last */
            if (--key_count > 0) html += ","
            html += "</li>"
          }
        }
        html += "</ul>}"
      } else {
        html += "{}"
      }
    }
    return html
  }
  // function madeTable(dataArray) {
  //   dataArray.map((item) => {
  //     Table().init({
  //       id: item.id,
  //       header: ["id", "姓名", "年龄"],
  //       data: [
  //         [1, "小王", 22],
  //         [2, "小李", 24],
  //         [3, "小郑", 19],
  //         [4, "小郑", 19],
  //         [5, "小郑", 19],
  //       ],
  //     })
  //   })
  // }
  let tableIdArray = []
  /**
   * jQuery plugin method
   * @param json: a javascript object
   * @param options: an optional options hash
   */
  $.fn.jsonViewer = function (json, options) {
    tableIdArray = []
    options = options || {}

    /* jQuery chaining */
    return this.each(function () {
      /* Transform to HTML */
      var html = json2html(json, options)
      if (isCollapsable(json)) html = '<a href class="json-toggle"></a>' + html

      /* Insert HTML in target DOM element */
      $(this).html(html)
      // madeTable(tableIdArray)
      /* Bind click on toggle buttons */
      $(this).off("click")
      $(this).on("click", "a.json-toggle", function () {
        var target = $(this).toggleClass("collapsed").siblings("ul.json-dict, ol.json-array")
        target.toggle()
        if (target.is(":visible")) {
          target.siblings(".json-placeholder").remove()
        } else {
          var count = target.children("li").length
          var placeholder = count + (count > 1 ? " items" : " item")
          target.after('<a href class="json-placeholder">' + placeholder + "</a>")
        }
        return false
      })

      /* Simulate click on toggle button when placeholder is clicked */
      $(this).on("click", "a.json-placeholder", function () {
        $(this).siblings("a.json-toggle").click()
        return false
      })

      if (options.collapsed == true) {
        /* Trigger click to collapse all nodes */
        $(this).find("a.json-toggle").click()
      }
    })
  }
})(jQuery)
